/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.gt.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.dao.AreaDao;
import com.thinkgem.jeesite.modules.sys.entity.Area;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.AreaService;
import com.thinkgem.jeesite.modules.sys.service.DictService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 区域Controller
 * @author zad
 * @version 2018-3-28
 */
@Controller
@RequestMapping(value = "${frontPath}/gt/area")
public class GtAreaController extends BaseController {

	@Autowired
	private AreaService areaService;
	@Autowired
	private DictService dictService;
	
	@Autowired
	private AreaDao areaDao;
	
	
	@ModelAttribute("area")
	public Area get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return areaService.get(id);
		}else{
			return new Area();
		}
	}

	@RequiresPermissions("user")
	@RequestMapping(value = {"list", ""})
	public String list(Area gtArea, String menuId, HttpServletRequest request, HttpServletResponse response, Model model) {
		//model.addAttribute("list", areaService.findAll());
		User user = UserUtils.getUser();
		Area p = user.getArea();
		/*Map<String,String> map = new HashMap<String, String>();
		map.put("dsf", " and ");*/
		gtArea.setParent(p);
		Page<Area> page = areaService.findPage(new Page<Area>(request, response), gtArea); 
		model.addAttribute("page", page);
		
		model.addAttribute("gtArea", gtArea);
		model.addAttribute("menuId", menuId);
		
		//////////////////////////////// 生成组织机构code
		/*Area param = new Area();
		param.setType("5");
		List<Area> areas = areaDao.findList(param);
		for(Area a : areas)
		{
			String pid = a.getParentId();
			Area parea = areaDao.get(pid);
			String areaName = a.getName();
			System.out.println(areaName);
			if(areaName.length() > 2)
			{
				if(areaName.endsWith("街道办事处"))
				{
					areaName = areaName.replace("街道办事处", "");
				}
				if(areaName.endsWith("镇"))
				{
					areaName = areaName.replace("镇", "");
				}
				if(areaName.endsWith("乡"))
				{
					areaName = areaName.replace("乡", "");
				}
			}
			String codePinyin = StringUtils.getPYIndexStr(areaName, false);
			String realCode = parea.getCode()+"." + codePinyin;
			System.out.println(realCode);
			Area ar = new Area();
			ar.setId(a.getId());
			ar.setCode(realCode);
			areaDao.update(ar);
		}*/
		///////////////////////////////
		
		// return "modules/sys/areaList";
		return "modules/gt/basic/gtAreaList";
		
	}

	@RequiresPermissions("user")
	@RequestMapping(value = "form")
	public String form(Area gtArea, Model model) {
		if (gtArea.getParent()==null||gtArea.getParent().getId()==null){
			gtArea.setParent(UserUtils.getUser().getArea());
		}
		gtArea.setParent(areaService.get(gtArea.getParent().getId()));
//		// 自动获取排序号
//		if (StringUtils.isBlank(area.getId())){
//			int size = 0;
//			List<Area> list = areaService.findAll();
//			for (int i=0; i<list.size(); i++){
//				Area e = list.get(i);
//				if (e.getParent()!=null && e.getParent().getId()!=null
//						&& e.getParent().getId().equals(area.getParent().getId())){
//					size++;
//				}
//			}
//			area.setCode(area.getParent().getCode() + StringUtils.leftPad(String.valueOf(size > 0 ? size : 1), 4, "0"));
//		}
		
		// 新增时，才设置序号
		if(StringUtils.isBlank(gtArea.getId()))
		{
			Integer maxSort = this.areaService.getMaxSort(gtArea.getParentId());
			if(null == maxSort)
			{
				maxSort = 2000;
			}
			gtArea.setSort(maxSort + 1);
		}
		
		Dict param = new Dict();
		param.setType("gt_area_type");
		List<Dict> types = this.dictService.findList(param);
		model.addAttribute("types", types);
		model.addAttribute("gtArea", gtArea);
		// return "modules/sys/areaForm";
		return "modules/gt/basic/gtAreaForm";
	}
	
	@RequiresPermissions("user")
	@RequestMapping(value = "save")
	public String save(Area gtArea, Model model, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/area";
		}
		if (!beanValidator(model, gtArea)){
			return form(gtArea, model);
		}
		areaService.save(gtArea);
		
		// 若更新的区域是当前操作员的区域，则同步更新登录的操作员信息
		User user = UserUtils.getUser();
		if(gtArea.getId().equals(user.getArea().getId()))
		{
			Area p = user.getArea().getParent();
			gtArea.setParent(p);
			UserUtils.getUser().setArea(gtArea);
		}
		
		addMessage(redirectAttributes, "保存区域'" + gtArea.getName() + "'成功");
		return "redirect:" + super.frontPath + "/gt/area?menuId=" + gtArea.getMenuId();
	}
	
	@RequiresPermissions("user")
	@RequestMapping(value = "delete")
	public String delete(Area gtArea,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + super.frontPath + "/gt/area?menuId=" + gtArea.getMenuId();
		}
//		if (Area.isRoot(id)){
//			addMessage(redirectAttributes, "删除区域失败, 不允许删除顶级区域或编号为空");
//		}else{
			areaService.delete(gtArea);
			request.setAttribute("title", "删除组织机构：" + gtArea.getName());
			addMessage(redirectAttributes, "删除区域成功");
//		}
		return "redirect:" + super.frontPath + "/gt/area?menuId=" + gtArea.getMenuId();
	}

	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Area> list = areaService.findAll();
		for (int i=0; i<list.size(); i++){
			Area e = list.get(i);
			if (StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1)){
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("name", e.getName());
				mapList.add(map);
			}
		}
		return mapList;
	}
	
	// add by zad 2018-03-31 根据部门查询子部门
		@RequestMapping("qrySubArea")
		public String qrySubArea(Area area, HttpServletRequest req,HttpServletResponse rsp)
		{
			String code = area.getParent().getCode();
			List<Area> areas = null;
			if(!StringUtils.isBlank(code))
			{
				String type = String.valueOf(code.split("\\.").length + 2);
				area.setType(type);
				// 查询自己的下级
				area.setCode(UserUtils.getUser().getArea().getCode());
				areas = this.areaService.findList(area);
				// 没有下级时
				if(null == areas || areas.size() < 1)
				{
					areas = new ArrayList<Area>();
					area.setCode("");
					area.setName("---请选择---");
					areas.add(area);
				}
			}
			String jsonStr = JsonMapper.toJsonString(areas);
			try {
				rsp.getWriter().print(jsonStr);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
}
